package com.creatingrevolutions.vbukit.lib;

import com.creatingrevolutions.vbukit.lib.handler.BaseVbukitHandler;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.RingtoneManager;
import android.net.Uri;

public class AudioUtil
{
	public void beep(Context context, final BaseVbukitHandler handler, int audioRes)
	{
		try {
			Uri soundUri = RingtoneManager
					.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
			
			MediaPlayer mMediaPlayer;
			
			if ( audioRes == -1 ) 
			{
				mMediaPlayer = new MediaPlayer();
				mMediaPlayer.setDataSource(context, soundUri);
				
				final AudioManager audioManager = (AudioManager) context
						.getSystemService(Context.AUDIO_SERVICE);
				if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0)
				{
					mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
					mMediaPlayer.setOnCompletionListener(new OnCompletionListener()
					{
						@Override
						public void onCompletion(MediaPlayer mp)
						{
							if ( handler != null ) {
								handler.updateInfo(true, null, null);
							}
						}
					});
					mMediaPlayer.setLooping(false);
					mMediaPlayer.prepare();
					mMediaPlayer.start();
				}
				else 
				{
					if ( handler != null ) {
						handler.updateInfo(false, null, null);
					}
				}
				
			} 
			else 
			{
				mMediaPlayer = MediaPlayer.create(context, audioRes);
				mMediaPlayer.start();
				if ( handler != null ) {
					handler.updateInfo(true, null, null);
				}
			}
			
		}
		catch ( Exception e ) 
		{
			e.printStackTrace();
			if ( handler != null ) {
				handler.updateInfo(false, null, null);
			}
		}
		
	}
	
	public void beep(Context context, final BaseVbukitHandler handler)
	{
		beep(context, handler, -1);
	}
}
